<template>
  <div class="project-template-container">
    <el-form
      ref="form"
      :model="projectForm"
      :rules="projectRules"
      label-position="top"
    >
      <el-form-item prop="name" label="项目名称">
        <el-input
          v-model="projectForm.name"
          placeholder="请输入文章标题"
        ></el-input>
      </el-form-item>

      <el-form-item prop="description" class="description-container">
        <template slot="label">
          <span>项目描述</span>
          <el-button
            class="desc-plus-btn"
            type="info"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="handlerDescPlus"
          ></el-button>
        </template>
        <el-input
          v-for="(t, i) in projectForm.description"
          :key="i"
          v-model="projectForm.description[i]"
          :placeholder="`请输入第${i + 1}条项目描述`"
        >
          <template slot="prepend">{{ `第${i + 1}条` }}</template>
          <template slot="append">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handlerDescDelete(i)"
            ></el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="项目链接" prop="url">
        <el-input v-model="projectForm.url" placeholder="请输入项目链接">
          <template slot="prepend">
            <div @click="isHttp = !isHttp" class="http-select">
              {{ isHttp ? "http://" : "https://" }}
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Github链接地址" prop="github">
        <el-input v-model="projectForm.github" placeholder="请输入Github地址">
          <template slot="prepend">{{ github_base }}</template>
        </el-input>
      </el-form-item>
      <el-form-item label="项目预览图">
        <div class="uploadimg-container">
          <UploadImg v-model="uploadimg" @onload="projectForm.thumb = $event" />
        </div>
      </el-form-item>
      <el-form-item label="排序等级" prop="order">
        <el-select v-model="projectForm.order" @change="handlerSelectChange">
          <el-option
            v-for="(c, i) in projectLevel"
            :key="i"
            :label="c"
            :value="i + 1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="handlerSubmitArticle">{{
          mode === "add" ? "新增项目" : "编辑项目"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UploadImg from "@/components/UploadImg";
import { setDevImg, stripProtocolAndHandleGitHub } from "@/utils";
import { mapGetters } from "vuex";
import { editProjectAPI, addProjectAPI } from "@/api/project";
export default {
  name: "ProjectTemplate",
  props: {
    mode: {
      type: String,
      validator: (v) => ["edit", "add"].includes(v),
      required: true,
    },
  },
  components: {
    UploadImg,
  },
  computed: {
    ...mapGetters(["projectFormEdit"]),
  },
  mounted() {
    if (this.mode === "edit") {
      this.getProjectDetaile();
    }
  },
  data() {
    let validateDescriptio = (r, v, c) => {
      if (v.length < 1) {
        c(new Error("请至少保留一条项目描述"));
      } else {
        v.forEach((t) => {
          if (t.trim().length < 1) {
            c(new Error("项目描述不能为空"));
            return;
          }
        });
        c();
      }
    };
    return {
      github_base: "https://github.com/",
      projectLevel: ["一级", "二级", "三级", "四级", "五级", "六级"],
      isHttp: true,
      uploadimg: "",
      projectForm: {
        name: "",
        description: [""],
        url: "",
        github: "",
        thumb: "",
        order: 1,
      },
      projectRules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        url: [{ required: true, message: "请输入项目链接", trigger: "blur" }],
        github: [
          { required: true, message: "请输入Github链接地址", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入项目描述", trigger: "blur" },
          { validator: validateDescriptio, trigger: "blur" },
        ],
        order: [
          { required: true, message: "请选择排序等级", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    setDevImg,
    handlerDescPlus() {
      this.projectForm.description.push("");
    },
    handlerDescDelete(index) {
      if (this.projectForm.description.length <= 1) {
        this.$message.warning("请至少保留一条项目描述");
        return;
      }
      this.projectForm.description.splice(index, 1);
    },
    getProjectDetaile() {
      const editSingleProject = { ...this.projectFormEdit };
      if (Object.keys(editSingleProject).length) {
        this.uploadimg = setDevImg(editSingleProject.thumb);
        this.projectForm = {
          ...editSingleProject,
          github: stripProtocolAndHandleGitHub(editSingleProject.github),
          url: stripProtocolAndHandleGitHub(editSingleProject.url),
        };
      }
    },
    handlerSubmitArticle() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.mode === "add") {
            // 新增项目
            const res = await addProjectAPI({
              ...this.projectForm,
              github: this.github_base + this.projectForm.github,
              url: this.isHttp ? "http://" : "https://" + this.projectForm.url,
            });
            if (typeof res !== "string") {
              this.$message.success("新增项目成功");
              this.$router.push({ path: "/project/projectlist" });
            } else {
              const { msg } = JSON.parse(res);
              this.$message.error(msg);
            }
          } else {
            // 编辑项目
            const res = await editProjectAPI(
              this.projectForm.id,
              this.projectForm
            );
            if (typeof res !== "string") {
              this.$message.success("项目更新成功");
              this.$router.push({ path: "/project/projectlist" });
              this.$store.dispatch("project/resetProjectForm");
            } else {
              const { msg } = JSON.parse(res);
              this.$message.error(msg);
            }
          }
        } else {
          return false;
        }
      });
    },
    handlerSelectChange() {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped lang="scss">
.http-select {
  height: 100%;
  width: 100%;
  cursor: pointer;
}
.description-container {
  ::v-deep .desc-plus-btn {
    margin-left: 5px;
  }
  ::v-deep .el-input-group__append {
    background-color: #f56c6c;
    .el-icon-delete {
      color: #fff;
      font-size: 16px;
      font-weight: 800;
    }
  }
}
</style>
